package com.zyx.context;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>上下文管理
 *
 * @author Yaxi.Zhang
 * @since 2022/10/7 11:12
 */
public class BaseContextHandler {
    private static final ThreadLocal<Map<String, String>> THREAD_LOCAL = new ThreadLocal<>();

    public static void set(String key, Long value) {
        Map<String, String> map = getLocalMap();
        map.put(key, value == null ? "0" : String.valueOf(value));
    }

    public static void set(String key, String value) {
        Map<String, String> map = getLocalMap();
        map.put(key, value == null ? "" : value);
    }

    public static void set(String key, Boolean value) {
        Map<String, String> map = getLocalMap();
        map.put(key, value == null ? "false" : value.toString());
    }

    public static Map<String, String> getLocalMap() {
        Map<String, String> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<>(10);
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, String> threadLocalMap) {
        THREAD_LOCAL.set(threadLocalMap);
    }

    public static Long getUserId() {
        Object value = get(BaseContextConstants.USER_ID);
        return Long.parseLong(value.toString());
    }

    public static void setUserId(Long userId) {
        set(BaseContextConstants.USER_ID, userId);
    }

    public static String getUserName() {
        Object value = get(BaseContextConstants.USER_NAME);
        return value == null ? "" : value.toString();
    }

    public static void setUserName(String userName) {
        set(BaseContextConstants.USER_NAME, userName);
    }


    public static String get(String key) {
        Map<String, String> map = getLocalMap();
        return map.getOrDefault(key, "");
    }

    private static String returnObjectValue(Object value) {
        return value == null ? "" : value.toString();
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }

}
